﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Inovout.RedictUrls;
using Inovout.Services;
using System.Net;
using System.Security.Cryptography;
using System.Net.Mail;
using Inovout.Runtime;

namespace Inovout.RedictUrls
{
    //实现类
    public class RedictUrlService : RepositoryService<RedirctUrl>, IRedictUrlService
    {
        protected RedictUrlRepository RedirctUrlRepository
        {
            get { return (RedictUrlRepository)base.Repository; }
        }
        public override void Save(RedirctUrl entity)
        {
            if (entity.Id == null)
            {
                //设置验证有效时间和最大次数
                entity.ValidNumber = 0;
                entity.LimitNumber = 1;
            }
            if (entity.ValidNumber == 0)
            {
                entity.ValidStartTime = DateTime.Now;
                entity.ValidEndTime = DateTime.Now.AddDays(7);
            }
            base.Save(entity);
        }

        public string SendMail(string mailPlate, Dictionary<string, string> contents, string subject)
        {
            string result = null;
            string smtpServer = ComponentRegistry.Resolve<IApplication>().Settings["SmtpServer"].ToString();
            string smtpUser = ComponentRegistry.Resolve<IApplication>().Settings["SmtpUser"].ToString();
            string smtpPassWord = ComponentRegistry.Resolve<IApplication>().Settings["SmtpPassWord"].ToString();

            string to = "moneywei_2008@163.com";
            string from = smtpUser;
            if (string.IsNullOrEmpty(subject))
            {
                subject = "3Cloud 新用户激活邮件";
            }

            string body = mailPlate;

            foreach (KeyValuePair<string, string> item in contents)
            {
                if (item.Key == "email")
                {
                    to = item.Value;
                }
                body = body.Replace("$(" + item.Key + ")", item.Value);
            }
            MailMessage message = new MailMessage(from, to, subject, body);
            SmtpClient client = new SmtpClient(smtpServer);
            client.Credentials = new System.Net.NetworkCredential(smtpUser, smtpPassWord);
            try
            {
                client.Send(message);
            }
            catch (Exception e)
            {
                result = "邮箱不可用。";
                throw e;
            }
            return result;
        }

        public RedirctUrl FindByActionUrl(string actionUrl)
        {
            return RedirctUrlRepository.FindByActionUrl(actionUrl);
        }

        public RedirctUrl FindByOrginalUrlByEamil(string email)
        {
            return RedirctUrlRepository.FindByOrginalUrlByEamil(email);
        }

        public RedirctUrl FindByOrginalUrlByMembershipUserId(int id)
        {
            return RedirctUrlRepository.FindByOrginalUrlByMembershipUserId(id);
        }

        private string GetLocalhostIp()
        {
            String strHostName = string.Empty;
            // Getting Ip address of local machine...
            // First get the host name of local machine.
            strHostName = Dns.GetHostName();
            Console.WriteLine("Local Machine's Host Name: " + strHostName);
            // Then using host name, get the IP address list..
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            return addr[0].ToString();
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time"> DateTime时间格式</param>
        /// <returns>Unix时间戳格式</returns>
        private int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// MD5 加密字符串
        /// </summary>
        /// <param name="rawPass">源字符串</param>
        /// <returns>加密后字符串</returns>
        private string MD5Encoding(string rawPass)
        {
            // 创建MD5类的默认实例：MD5CryptoServiceProvider
            MD5 md5 = MD5.Create();
            byte[] bs = Encoding.UTF8.GetBytes(rawPass);
            byte[] hs = md5.ComputeHash(bs);
            StringBuilder sb = new StringBuilder();
            foreach (byte b in hs)
            {
                // 以十六进制格式格式化
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }
    }
}
